const User = require('../../models/User');
const Message = require('../../models/Message');
const Hourse = require('../../models/Hourse');
const {Op} = require('sequelize');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const dayjs = require('dayjs');
const config = require('../../config/config');
const Admin = require('../../models/Admin');
require('../../models/association');

const UserAddMiddleWare = (req,res)=>{
    let {name,idcard,phone,permissions,password} = req.body;
    password = bcrypt.hashSync(password,8);
    User.create({name,id_card:idcard,phone,permissions,password}).then(
        val=>{
            console.log("val ",val);
            res.send({id:val.dataValues.id});
        }
    ).catch(err=>{
        console.log("err ",err);
        res.send({err});
    });
}

const UserLoginMiddleWare = (req,res)=>{
    let {phone,password} = req.body;
    User.findAll({
        where:{
            phone
        }
    }).then(values=>{
        if(values.length !==0){
            if(bcrypt.compareSync(password,values[0].dataValues.password)){
                console.log(values[0].dataValues);
                const tokenStr = jwt.sign({ permissions:values[0].dataValues.permissions,id:values[0].dataValues.id }, config.jwtSecretKey, {
                    expiresIn: '24h', //token有效期24小时
                });
                res.status(200).send({
                    message: '登录成功',
                    //为了方便客户端的使用token,所以在服务器端直接拼接上'Bearer '(有一个空格)的前缀。
                    token: 'Bearer ' + tokenStr,
                    id:values[0].dataValues.id
                });
            }else{
                res.status(422).send({
                    message: "账号密码错误"
                });
            }
        }else{
            res.status(422).send({
                message: "账号密码错误"
            });
        }
    }).catch(err=>{
        console.log("err ",err);
        res.send('error');
    });
}

const UserSearchByIdMiddleWare  = (req,res)=>{
    let {id} = req.params;
    User.findOne({
        where:{
            id
        }
    }).then(values=>{
        let user = values.dataValues;
        delete user.password;
        delete user.id_card;
        res.send({
            user
        })
    }).catch(err=>{
        res.send({err:err.message});
    })
}

const UserHoursePicMiddleWare = (req, res) => {
    const file = req.file;
    file.url = `http://localhost:22222/uploads/${file.filename}`;
    res.send(file);
}

const UserAddHourseMiddleWare = (req,res) =>{
    let {userId,mianji,floor,rent,model,huxin,direction,around,decorate,owner,phone,pic,address} = req.body;
    let time = new Date();
    Hourse.create({
        user_id:userId,
        mianji,floor,rent,model,huxin,direction,around,decorate,owner,phone,pic,
        create_time:time,
        update_time:time,
        address
    }).then(val=>{
        console.log('val ',val);
    }).catch(err=>{
        console.log("err");
    });
    res.send('success');
}

const UserSelectAllHourseMiddleWare = (req,res)=>{
    let {id} = req.params;
    Hourse.findAll({
        where:{
            user_id:id
        }
    }).then(val=>{
        return val.map(hourse=>{
            return hourse.dataValues;
        });
    }).then(hourse=>{
        let h = hourse.map(hourse=>{
            hourse.create_time = dayjs(hourse.create_time).format('YYYY-MM-DD HH:mm');
            hourse.update_time = dayjs(hourse.update_time).format('YYYY-MM-DD HH:mm');
            return hourse;
        })
        res.send(h);
    });
}

const SelectHourseByUserIdAndHourseIdMiddleWare = (req,res)=>{
    let {uid,hid} = req.body;
    Hourse.findOne({
        where:{
            [Op.and]:[
                {id:hid},
                {user_id:uid}
            ]
        }
    }).then(val=>{
        res.send(val.dataValues);
    });
}

const updateHourseByTwoIdMiddleWare = (req,res)=>{
    let {uid,hid,mianji,floor,rent,model,huxin,direction,around,decorate,owner,phone,pic,address} = req.body;
    let time = new Date();
    Hourse.update({mianji,floor,rent,model,huxin,direction,around,decorate,owner,phone,pic,address,update_time:dayjs(time).format('YYYY-MM-DD HH:mm:ss')},{
        where:{
            [Op.and]:[
                {user_id:uid},
                {id:hid}
            ]
        }
    }).then(val=>{
    }).catch(err=>{
    });
    res.send("success");
}

const GetAllUserMiddleWare = (req,res)=>{
    console.log("GetAllUserMiddleWare");
    User.findAll().then(val=>val.map(v=>v.dataValues)).then(users=>{
        console.log("users ",users);
        let result = users.map(u=>{
            delete u.password;
            return u;
        });
        res.send(result);
    })
}

const deleteHourseByHourseIdMiddleWare = (req,res)=>{
    let {id} =req.params;
    Hourse.destroy({
        where:{
            id
        }
    }).then(val=>{
        console.log("val ",val);
    }).catch(err=>{
        console.log("err ",err);
    });
    Message.destroy({
        where:{
            hourse_id:id
        }
    }).then(val=>{
        console.log("val ",val);
    }).catch(err=>{
        console.log("err ",err);
    });
    res.send('success');

}

const selectAllHourseMiddleWare = (req,res)=>{
    Hourse.findAll().then(val=>val.map(v=>v.dataValues)).then(hourse=>{res.send(hourse)});
}

const updateUserPermissionByUserIdMiddleWare = (req,res)=>{
    let {id,permissions} =req.body;
    console.log("permissions\n",permissions);
    User.update({permissions},{
        where:{
            id
        }
    }).then(val=>{
        return User.findAll();
    }).then(val=>{
        return val.map(v=>v.dataValues);
    }).then(v=>{
        res.send(v);
    })
    .catch(err=>{
        console.log("err ",err);
    })
}

const selectHourseByHidMiddleWare = (req,res)=>{
    let {id} = req.params;
    Hourse.findOne({
        where:{
            id
        }
    }).then(val=>{
        res.send(val.dataValues);
    });
}

const selectHoursesByHNameMiddleWare = (req,res)=>{
    let {name} = req.body;
    Hourse.findAll({
        where:{
            address:{
                [Op.like]:'%'+name+'%'
            }
        }
    }).then(val=>{
        if(!val.length==0){
            return val.map(v=>v.dataValues);
        }
        res.send({});
    }).then(v=>{
        res.send(v);
    });
}

const selectHoursesByhuxinMiddleWare = (req,res)=>{
    let {huxin} = req.body;
    Hourse.findAll({
        where:{
            huxin:{
                [Op.like]:`%${huxin}%`
            }
        }
    }).then(val=>{
        if(!val.length==0){
            return val.map(v=>v.dataValues);
        }
        res.send({});
    }).then(v=>{
        res.send(v);
    });
}
const selectHoursesBymodelMiddleWare = (req,res)=>{
    let {model} = req.body;
    Hourse.findAll({
        where:{
            model:{
                [Op.like]:`%${model}%`
            }
        }
    }).then(val=>{
        if(!val.length==0){
            return val.map(v=>v.dataValues);
        }
        res.send({});
    }).then(v=>{
        res.send(v);
    });
}

const selectHoursesByDirectionMiddleWare = (req,res)=>{
    let {direction} = req.body;
    Hourse.findAll({
        where:{
            direction
        }
    }).then(val=>{
        if(!val.length==0){
            return val.map(v=>v.dataValues);
        }
        res.send({});
    }).then(v=>{
        res.send(v);
    });
}
const selectHoursesByDecorateMiddleWare = (req,res)=>{
    let {decorate} = req.body;
    Hourse.findAll({
        where:{
            decorate
        }
    }).then(val=>{
        if(!val.length==0){
            return val.map(v=>v.dataValues);
        }
        res.send({});
    }).then(v=>{
        res.send(v);
    });
}

module.exports = {
    UserAddMiddleWare,
    UserLoginMiddleWare,
    UserSearchByIdMiddleWare,
    UserHoursePicMiddleWare,
    UserAddHourseMiddleWare,
    UserSelectAllHourseMiddleWare,
    SelectHourseByUserIdAndHourseIdMiddleWare,
    updateHourseByTwoIdMiddleWare,
    deleteHourseByHourseIdMiddleWare,
    selectAllHourseMiddleWare,
    GetAllUserMiddleWare,
    updateUserPermissionByUserIdMiddleWare,
    selectHourseByHidMiddleWare,
    selectHoursesByHNameMiddleWare,
    selectHoursesByhuxinMiddleWare,
    selectHoursesBymodelMiddleWare,
    selectHoursesByDirectionMiddleWare,
    selectHoursesByDecorateMiddleWare
}